﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebPartPages;
using zevenseas.LifeCycleManagement.Utilities;

namespace zevenseas.LifeCycleManagement.EventReceivers
{
    public class CreateLCMWebFeatureReceiver : SPFeatureReceiver 
    {
        private ErrorHandling errorHandling;

        public CreateLCMWebFeatureReceiver()
        {           
            errorHandling = new ErrorHandling();
            errorHandling.productName = "CreateLCMWebFeatureReceiver";
            errorHandling.exeName = "zevenseas.LifeCycleManagement.EventReceivers";
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPAdministrationWebApplication webApplication = SPAdministrationWebApplication.Local;
            using (SPWeb currentWeb = webApplication.Sites[0].RootWeb)
            {
                CreateWeb(currentWeb);
                CreateList(currentWeb);
                AddWebParts(currentWeb);
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            ////SPAdministrationWebApplication webApplication = SPAdministrationWebApplication.Local;
            ////SPWeb currentWeb = webApplication.Sites[0].RootWeb;
            
            ////DeleteWeb(currentWeb);
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

        private void DeleteWeb(SPWeb web)
        {
            try
            {
                //web.Site.AllWebs["LCM"].Delete();                
            }
            catch (Exception siteCreationError)
            {
                errorHandling.LogMessage(siteCreationError.Message.ToString(), siteCreationError);
            }
        }

        private void CreateWeb(SPWeb web)
        {
            try
            {
                SPWebApplication centralAdminWebApplication = SPAdministrationWebApplication.Local;
                SPWeb centralAdminWeb = centralAdminWebApplication.Sites[0].RootWeb;

                SPGroup adminUsers = centralAdminWeb.SiteGroups["Farm Administrators"];
                string centralAdminApplicationPoolAccount = centralAdminWebApplication.ApplicationPool.Username;

                List<string> applicationPoolAccounts = new List<string>();

                SPWebApplicationCollection webApplicationCollection = SPWebService.ContentService.WebApplications;
                foreach (SPWebApplication webApplication in webApplicationCollection)
                {
                    if (!applicationPoolAccounts.Contains(webApplication.ApplicationPool.Username))
                    {
                        applicationPoolAccounts.Add(webApplication.ApplicationPool.Username);
                    }
                }


                if (!Utilities.Utilities.DoesWebExist(centralAdminWebApplication))
                {
                    SPWeb LCMweb = centralAdminWeb.Webs.Add("LCM", "Life Cycle Management Logging and Analytical Site", "", Convert.ToUInt32(1033), "STS#0", true, false);
                    
                    LCMweb.CreateDefaultAssociatedGroups(centralAdminApplicationPoolAccount, "", "");
                    foreach (string applicationPoolAccount in applicationPoolAccounts)
                    {
                        LCMweb.AssociatedOwnerGroup.AddUser(applicationPoolAccount, "", "", "");
                    }

                    foreach (SPUser user in adminUsers.Users)
                    {
                        LCMweb.AssociatedOwnerGroup.AddUser(user);
                    }
                }
                
                Utilities.Utilities.SetWebProperty("true", "LCMSiteCreated", web.Properties);
            }
            catch (Exception siteDeletionnError)
            {
                Utilities.Utilities.SetWebProperty("false", "LCMSiteCreated", web.Properties);
                errorHandling.LogMessage(siteDeletionnError.Message.ToString(), siteDeletionnError);
            }
        }

        private void CreateList(SPWeb web)
        {
            using (SPWeb LCMWeb = web.Webs["LCM"])
            {
                if (!Utilities.Utilities.DoesListExist(LCMWeb, "DeletedSites"))
                {
                    Utilities.Utilities.CreateList(LCMWeb, 
                        "DeletedSites", 
                        "Overview of all the sites and webs that have been deleted", 
                        zevenseas.LifeCycleManagement.Utilities.Utilities.List.DeletedSitesList);
                }

                if (!Utilities.Utilities.DoesListExist(LCMWeb, "WebApplications"))
                {
                    Utilities.Utilities.CreateList(
                        LCMWeb, 
                        "WebApplications", 
                        "Overview of all the WebApplications", 
                        zevenseas.LifeCycleManagement.Utilities.Utilities.List.WebApplication);
                  
                }

                if (!Utilities.Utilities.DoesListExist(LCMWeb, "UnusedSites"))
                {
                    Utilities.Utilities.CreateList(
                        LCMWeb, 
                        "UnusedSites", 
                        "Overview of all the sites that are not being used for a period of time", 
                        zevenseas.LifeCycleManagement.Utilities.Utilities.List.UnusedSitesList);
                }
            }
        }

        private void AddWebParts(SPWeb web)
        {
            using (SPWeb LCMWeb = web.Webs["LCM"])
            {
                SPList deletedSitesList = LCMWeb.Lists["DeletedSites"];
                SPList unusedSitesList = LCMWeb.Lists["UnusedSites"];

                ListViewWebPart deletedSitesWebPart = Utilities.Utilities.CreateListViewWebPart(deletedSitesList);
                ListViewWebPart unusedSitesWebPart = Utilities.Utilities.CreateListViewWebPart(unusedSitesList);

                SPLimitedWebPartManager webpartManager = LCMWeb.GetLimitedWebPartManager("default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                webpartManager.AddWebPart(deletedSitesWebPart, "Left", 1);
                webpartManager.AddWebPart(unusedSitesWebPart, "Left", 2);


                Utilities.Utilities.DisableToolbar(deletedSitesWebPart);
                Utilities.Utilities.DisableToolbar(unusedSitesWebPart);
            }
        }
    }
}
